package com.mobile.web.businessDocument;

import com.mobile.service.dto.BusinessDocumentDTO;
import com.mobile.service.dto.BusinessDocumentQueryDTO;
import com.mobile.service.inter.BusinessDocumentService;
import com.mobile.util.*;
import com.mobile.web.base.BaseController;
import com.mobile.util.config.aop.AutoFill;
import com.mobile.util.config.aop.OperateType;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务文书表API接口
 */
@RestController
@RequestMapping("/businessDocument")
@Tag(name = "业务文书管理接口", description = "包含业务文书的查询、新增、修改、删除等操作")
public class BusinessDocumentController extends BaseController {

    @Autowired
    private BusinessDocumentService businessDocumentService;

    @PostMapping("/addBusinessDocument")
    //@RequiresPermissions("businessDocumentmana:add:1")
    @Operation(summary = "创建业务文书")
    @AutoFill(OperateType.INSERT)
    public Object addBusinessDocument(@Valid @RequestBody BusinessDocumentDTO dto) {
        Map<String, Object> map;
        try {
            map = businessDocumentService.addBusinessDocument(dto);
        } catch (Exception e) {
            map = new HashMap<>();
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }
        return AppUtil.returnObject(map);
    }

    @GetMapping(value = "/getBusinessDocumentListPage")
    //@RequiresPermissions("businessDocumentmana:read:1")
    @Operation(summary = "分页查询业务文书")
    public Object getBusinessDocumentListPage(@Validated BusinessDocumentQueryDTO queryDTO) {
        Map<String, Object> map = new HashMap<>();
        try {
            PageResult<BusinessDocumentDTO> page = businessDocumentService.getBusinessDocumentListPage(queryDTO);
            map.put("page", page);
            map.put("data", page.getPageDatas());
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
        } catch (Exception e) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }
        return AppUtil.returnObject(map);
    }

    @GetMapping(value = "/getBusinessDocumentById")
    //@RequiresPermissions("businessDocumentmana:edit:1")
    @Operation(summary = "查询业务文书详情")
    public Object getBusinessDocumentById(
        @Parameter(description = "业务文书主键", required = true) 
        @RequestParam("documentId") Integer id) {
        Map<String, Object> map = new HashMap<>();
        try {
            BusinessDocumentDTO dto = businessDocumentService.getBusinessDocumentById(id);
            if (StringUtil.isEmpty(dto)) {
                map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
                map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0001"));
            } else {
                map.put("data", dto);
                map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
            }
        } catch (Exception e) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }
        return AppUtil.returnObject(map);
    }

    @PostMapping("/updateBusinessDocument")
    //@RequiresPermissions("BusinessDocumentmana:edit:1")
    @Operation(summary = "编辑业务文书")
    @AutoFill(OperateType.UPDATE)
    public Object updateBusinessDocument(@Valid @RequestBody BusinessDocumentDTO dto) {
        Map<String, Object> map;
        try {
            map = businessDocumentService.updateBusinessDocument(dto);
        } catch (Exception e) {
            map = new HashMap<>();
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }
        return AppUtil.returnObject(map);
    }

    @GetMapping("/removeBusinessDocument")
    //@RequiresPermissions("businessDocumentmana:delete:1")
    public Object removeBusinessDocument(@RequestParam("documentId") Integer id) {
        Map<String, Object> map;
        try {
            map = businessDocumentService.removeBusinessDocument(id);
        } catch (Exception e) {
            map = new HashMap<>();
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }
        return AppUtil.returnObject(map);
    }

    @GetMapping("/getBusinessDocumentList")
    //@RequiresPermissions("businessDocumentmana:read:1")
    @Operation(summary = "条件查询业务文书列表")
    public Object getBusinessDocumentList(@Valid @RequestBody BusinessDocumentDTO dto) {
        Map<String, Object> map = new HashMap<>();
        try {
            List<BusinessDocumentDTO> list = businessDocumentService.getBusinessDocumentList(dto);
            map.put("data", list);
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
        } catch (Exception e) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }
        return AppUtil.returnObject(map);
    }

    @GetMapping("/downloadDocument")
    @Operation(summary = "下载业务处理文书")
    public void downloadDocument(
            @RequestParam Integer workOrderId,
            @RequestParam Integer documentId,
            HttpServletResponse response) {
        try {
            // 从数据库查询文书信息
            BusinessDocumentDTO document = businessDocumentService.getBusinessDocumentById(documentId);

            if (document == null) {
                logger.warn("未找到对应的文书，工单ID: {}，文档ID: {}", workOrderId, documentId);
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "未找到对应的文书");
                return;
            }

            // 获取文件路径
            String filePath = document.getFilePath();
            if (StringUtil.isEmpty(filePath)) {
                logger.error("文书文件路径为空，工单ID: {}，文档ID: {}", workOrderId, documentId);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "文书文件路径不存在");
                return;
            }

            // 构造完整文件路径
            String fullPath = System.getProperty("user.dir") + filePath;
            File file = new File(fullPath);

            // 检查文件是否存在
            if (!file.exists()) {
                logger.error("文书文件不存在，文件路径: {}", fullPath);
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "文书文件不存在");
                return;
            }

            // 设置响应头
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=" +
                    java.net.URLEncoder.encode(document.getFileName(), "UTF-8"));
            response.setContentLength((int) file.length());

            // 读取文件并写入响应
            try (FileInputStream fis = new FileInputStream(file);
                 BufferedInputStream bis = new BufferedInputStream(fis)) {
                BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = bis.read(buffer)) != -1) {
                    bos.write(buffer, 0, bytesRead);
                }
                bos.flush();
            }

            logger.info("文书下载成功，工单ID: {}，文件名: {}", workOrderId, document.getFileName());
        } catch (Exception e) {
            logger.error("下载文书失败，工单ID: {}，文档ID: {}", workOrderId, documentId, e);
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "文书下载失败");
            } catch (Exception ex) {
                logger.error("发送错误响应失败", ex);
            }
        }
    }


    @GetMapping(value = "/createDocument")
    @Operation(summary = "生成并保存业务处理文书")
    public void getDocument(
            @RequestParam Integer workOrderId) {

        businessDocumentService.generateAndSaveBusinessDocument(workOrderId);
    }
}
